﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SimpleJSON;

using System.Threading;

public class BaseSubscriber : MonoBehaviour {

	// Use this for initialization
    [HideInInspector]
    public string topic;
    [HideInInspector]
    public string messageType;

    public bool BigData=false;

    public int minProcessIntervalMillSeconds=1000;

    private Thread parserThread;

    public List<JSONNode> needParse;

    private List<ROSBridgeMsg> parsed;


	void Start () {
        
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}




    void OnEnable()
    {


        needParse= new List<JSONNode>();

        parsed=new List<ROSBridgeMsg>();


        parserThread=new Thread(ParseProcess);

        parserThread.Start();


    }

    void OnDisable()
    {


        parserThread.Abort();

    }


    void ParseProcess()
    {

        while (true)
        {

            JSONNode node=null;

            lock(needParse)
            {

                if (needParse.Count>0)
                {

                    node=needParse[0];

                    needParse.RemoveAt(0);
                }


            }




            if (node!=null)
            {

                ROSBridgeMsg rosMsg=Parse(node);


                lock(parsed)
                {

                    parsed.Add(rosMsg);


                }

            }
            else
            {


                Thread.Sleep(minProcessIntervalMillSeconds);

            }

        }



    }



    public virtual ROSBridgeMsg Parse(JSONNode msg)
    {

        throw new UnityException("Not implement parse function");


    }





    public string GetMsgHead()
    {

        return "{\"topic\": \""+topic+"\"";

    }


    public  void AddToNeedParse(JSONNode msg)
    {


        lock(needParse)
        {

            needParse.Add(msg);
   
        }

    }

    public virtual void OnMessage ()
    {
     


    }


    public ROSBridgeMsg GetTopParsedPackage()
    {

        ROSBridgeMsg pack=null;

        if (parsed.Count==0)

        {

            return null;

        }

        lock(parsed)
        {
            if (parsed.Count>0)
            {

                pack=parsed[0];

                parsed.RemoveAt(0);

            }
        }

        return pack;

       
    }


    public virtual void OnNavFinish()
    {



    }

    public virtual void OnReset()
    {



    }




}
